package bs

import scala.xml.NodeSeq
import net.liftweb._
import http._
import util._
import Helpers._

class Tooltip(val title: String) extends (NodeSeq => NodeSeq) {
  def generateId = s"tooltip-${(math.random * 100).toInt}"
  def script(id: String) = s"$$('#$id').tooltip();"
  def default = "* [title]" #> title & "* [data-toggle]" #> "tooltip"

  val transformers = collection.mutable.Buffer(default)

  override def apply(v1: NodeSeq): NodeSeq = {
    // 使用 \ 取唯一顶级元素的id，要求v1有唯一顶级元素。
    val id = Option((v1 \ "@id").text).filter(_.nonEmpty).getOrElse {
      val _id = generateId
      transformers += "* [id]" #> _id
      _id
    }
    transformers.reduce(_ & _).apply(v1) ++ <script type="text/javascript" data-lift="tail">{script(id)}</script>
  }

  def atLeft = {
    transformers += "* [data-placement]" #> "left"
    this
  }

  def atRight = {
    transformers += "* [data-placement]" #> "right"
    this
  }

  def atTop = {
    transformers += "* [data-placement]" #> "top"
    this
  }

  def atBottom = {
    transformers += "* [data-placement]" #> "bottom"
    this
  }

  def triggerByClick = {
    transformers += "* [data-trigger]" #> "click"
    this
  }

  def triggerByHover = {
    transformers += "* [data-trigger]" #> "hover"
    this
  }

  def triggerByFocus = {
    transformers += "* [data-trigger]" #> "focus"
    this
  }

  def triggerManually = {
    transformers += "* [data-trigger]" #> "manual"
    this
  }
}

object Tooltip {
  def apply(title: String) = new Tooltip(title)
}

case class Popover(override val title: String, content: NodeSeq) extends Tooltip(title) {
  override val generateId = s"popover-${(math.random * 100).toInt}"
  override def script(id:String) = s"""$$('#$id').popover();"""

  override def default = super.default & "* [data-content]" #> content & "* [data-toggle]" #> "popover"


}
